import type { GridApi } from '@ag-grid-community/core';
import { ready, assert, getApiPath } from '@/lib/utils.ts';
import { createAndInitilalizeTable } from '@/components/table/lib';
import {
    tf,
    questionMarkHeaderComponentParams,
} from '@/components/table/lib';

import {
    GridContextMenu,
    defaultMenuEntries,
} from "@/components/table/components/context-menu";

import { postJson } from '@/lib/request';


function initializeTable(url: string) {
    const table_elem = document.getElementById("table");
    assert(table_elem, "Element with ID 'table' not found");

    return createAndInitilalizeTable(url, table_elem, {
        onCellContextMenu: (event) => {
            const existingMenus = document.querySelectorAll('[data-ag-grid-context-menu]');
            existingMenus.forEach(menu => menu.remove());
        
            const gridContextMenu = new GridContextMenu(event.api,
                defaultMenuEntries.concat([
                    {
                        label: "copy",
                        text: gettext("复制注册链接"),
                        callback: (context) => {
                            if (!context) return;
                            const code = context.data['code'];
                            const registryLink = `${window.location.origin}/user/signup?code=${code}`
                            navigator.clipboard.writeText(registryLink);
                        },
                        enabled: (context) => {
                            // Check browser support and cell content existence
                            const canCopy = 'clipboard' in navigator;
                            return !!context && canCopy && context.value != null;
                        }
                    }
                ])
            );
            gridContextMenu.onCellContextMenu(event);
        },
        rowSelection: { 
            mode: 'multiRow' 
        },
        columnDefs: [
            {
                ...tf("code", "邀请码"),
                headerComponentParams: questionMarkHeaderComponentParams,
                headerTooltip: gettext("用邀请码注册的用户不会经过管理员审核"),
                minWidth: 200,
                flex: 1,
            },
            {
                ...tf("max_uses", "最大使用次数"),
                cellRenderer: (params: any) => params.value ? params.value: `∞`,
                width: 150,
            },
            {
                ...tf("times_used", "已使用次数"),
                width: 150,
            },
            {
                ...tf("created_by", "创建者"),
                width: 150,
            },
            {
                ...tf("created_at", "创建时间"),
                type: 'date',
            }
        ]
    });
}

export async function deleteSelectedInviteCodes(gridApi: GridApi) {
    const selected_rows = gridApi.getSelectedNodes();
    const code_ids = selected_rows.map(node => node.data.code);

    if (code_ids.length === 0) {
        alert(gettext("没有需要删除的邀请码"));
        return;
    }

    try {
        await postJson('/api/user/management/invite-code/delete', code_ids);

        alert(gettext("删除成功"));
        window.location.reload();
    } catch (error) {
        // Error already handled by request function
    }
}


(function () {
    ready(() => {
        const gridApi = initializeTable(getApiPath());

        const delete_selected_btn_elem = document.getElementById("delete-selected-btn")!;
        delete_selected_btn_elem.addEventListener("click", () => {
            deleteSelectedInviteCodes(gridApi);
        });
    });
})();
